﻿using System.Linq;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Services.Client;

namespace PictureService
{
    public class PictureEntity : TableServiceEntity
    {

        public PictureEntity(string partitionKey, string rowKey)
            : base(partitionKey, rowKey)
        {
        }

        public PictureEntity()
            : base()
        {
        }

        public string SyndicationItem
        {
            get;
            set;
        }
    }

    public class PictureDataServiceContext : TableServiceContext
    {
        public static string PictureTableName = "PictureTable";

        internal PictureDataServiceContext(string baseAddress, StorageCredentials credentials)
            : base(baseAddress, credentials)
        {
        }

        public IQueryable<PictureEntity> PictureTable
        {
            get
            {
                return this.CreateQuery<PictureEntity>(PictureTableName);
            }
        }
    }

    public class PictureDataSource
    {
        private PictureDataServiceContext context;

        public PictureDataSource()
        {
            CloudStorageAccount storageAccount = 
                CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            context = new PictureDataServiceContext(storageAccount.TableEndpoint.AbsoluteUri,
                storageAccount.Credentials);
            context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));

        }

        public IEnumerable<PictureEntity> ReadAllPictures()

        {
            return from c in context.PictureTable select c;
        }



        public PictureEntity ReadPicture(string id)
        {
            var results = from c in context.PictureTable 
                          where c.PartitionKey == "" && c.RowKey == id
                          select c;

            try
            {
                return results.SingleOrDefault<PictureEntity>();
            }   
            catch (DataServiceQueryException)
            {
                return null;
            }
        }

        public void CreatePicture(PictureEntity picture)
        {
            context.AddObject(PictureDataServiceContext.PictureTableName, picture);
            context.SaveChanges();
        }

        public void UpdatePicture(PictureEntity oldPicture)
        {
            context.UpdateObject(oldPicture);
            context.SaveChanges();
        }

        public void DeletePicture(PictureEntity picture)
        {
            context.DeleteObject(picture);
            context.SaveChanges();
        }
    }
}